package com.yanyu.space.common.db.pagination;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author yanyu
 */
class PageContext {

    private static final ThreadLocal<IPage> PAGE = new ThreadLocal<>();

    public static <T> void set(HttpServletRequest request) {
        Integer pageNum = Optional.ofNullable(request.getParameter("pageNum")).map(item -> Integer.valueOf(item)).orElse(1);
        Integer pageSize = Optional.ofNullable(request.getParameter("pageSize")).map(item -> Integer.valueOf(item)).orElse(20);
        IPage<T> page = new Page<>(pageNum, pageSize);
        PAGE.set(page);
    }

    public static <T> void set(Integer pageNum, Integer pageSize) {
        IPage<T> page = new Page<>(pageNum, pageSize);
        PAGE.set(page);
    }

    public static <T> void setMax() {
        IPage<T> page = new Page<>(0, 5000);
        PAGE.set(page);
    }

    public static <T> IPage<T> get() {
        return PAGE.get();
    }

    public static void clear() {
        PAGE.remove();
    }
}
